<?php

class OpinionControllerCore extends FrontController {

    public $php_self = 'opinion.php';

    public function setMedia() {
        parent::setMedia();
        Tools::addCSS(_THEME_CSS_DIR_ . 'opinion.css');
        Tools::addCSS(_THEME_CSS_DIR_ . 'jquery.rating.css');
        Tools::addJS(_THEME_JS_DIR_ . 'jquery.rating.pack.js');
    }

    public function process() {
        parent::process();
        $errors = null;
        $success = null;
        if (isset($_POST['save_opinion'])) {
            if (Tools::getValue('opinion_name') == '') {
                $errors['opinion_name'] = 'Proszę podać imię lub pseudonim';
            }

            if ((int) Tools::getValue('opinion_rating') == 0) {
                $errors['opinion_rating'] = 'Proszę wybrać jedną z opcji';
            }

            if (Tools::getValue('opinion_message') == '') {
                $errors['opinion_message'] = 'Proszę uzupełnić treść';
            }

            if (empty($errors)) {
                $name = strip_tags(trim(Tools::getValue('opinion_name')));
                $rating = (int) Tools::getValue('opinion_rating');
                $message = strip_tags(Tools::getValue('opinion_message'));

                $result = Db::getInstance()->Execute('INSERT INTO ' . _DB_PREFIX_ . 'opinion (`name`, `rating`, `message`, `created_at`) 
                        VALUES ("' . $name . '", ' . $rating . ', "' . $message . '", "' . date('Y-m-d H:i:s', time()) . '")');
                if (!$result) {
                    $error = 'Przepraszamy! Wystąpił problem z zapisem Twojej opinii.';
                } else {
                    $success = 'Dziękujemy! Twoja opinia została zapisana i wkrótce pojawi się na stronie.';
                }
            }
        }
        self::$smarty->assign(array(
            'opinion_errors' => $errors,
            'write_error' => $error,
            'success' => $success
        ));
    }

    public function displayContent() {
        parent::displayContent();
        self::$smarty->display(_PS_THEME_DIR_ . 'opinion.tpl');
    }

}
